package com.jhgsys.internal.sypq.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.jhgsys.internal.common.annotation.Log;
import com.jhgsys.internal.common.controller.BaseController;
import com.jhgsys.internal.common.entity.FebsResponse;
import com.jhgsys.internal.common.utils.Plupload;
import com.jhgsys.internal.common.utils.PluploadUtil;
import com.jhgsys.internal.common.utils.UploadPathUtil;
import com.jhgsys.internal.sypq.entity.ModelShipProcess;
import com.jhgsys.internal.sypq.entity.TaskDto;
import com.jhgsys.internal.sypq.params.ShipModelProcParams;
import com.jhgsys.internal.sypq.params.WechatFinishParams;
import com.jhgsys.internal.sypq.params.WechatModelParams;
import com.jhgsys.internal.sypq.service.*;
import com.jhgsys.internal.sypq.vo.*;
import com.jhgsys.internal.system.entity.User;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

/**
 * @ClassName WechatController
 * @Description 企业微信端controller
 * @Author Lucas
 * @Date 2024/12/7
 **/
@Slf4j
@Validated
@Controller
@CrossOrigin
@RequestMapping("/wechat")
@Tag(description = "企业微信端controller",name = "WechatController")
public class WechatController extends BaseController {

    // 文件允许格式
    private final String[] allowImageFiles = {".gif", ".png", ".jpg", ".jpeg", ".bmp" };
    private final String[] allowVideoFiles = {".swf", ".wmv", ".mpg", ".m4v", ".mp4", ".flv", ".3gp", ".avi", ".rmvb", ".mkv"};
    private final String[] allowOtherFiles = {".rar", ".zip", ".pdf", ".txt", ".ppt", ".pptx", ".doc", ".docx", ".xls", ".xlsx", ".gif", ".png", ".jpg", ".jpeg", ".bmp" };

    @Resource
    private IModelShipService modelShipService;

    @Resource
    private IModelOarsService modelOarsService;

    @Resource
    private IModelAttachService modelAttachService;
    @Autowired
    private IScheduleService scheduleService;

     @CrossOrigin
    @GetMapping("/getShipModelList")
    @ResponseBody
    @Operation(summary = "企业微信端船模列表", description = "企业微信端船模列表", tags = {"WechatController"})
    @ApiResponses(value = {@ApiResponse(responseCode = "200",description = "",content ={@Content(schema = @Schema(implementation = WechatShipModelVO.class))} )})
    public FebsResponse getShipModelList(@Parameter(name = "船模列表查询参数",description = "JSON格式",required = true)WechatModelParams params){
        List<WechatShipModelVO> list =  modelShipService.getShipModelList(params);
        return success(list);
    }

    @CrossOrigin
    @GetMapping("/getShipModelProcs")
    @ResponseBody
    @Operation(summary = "企业微信端船模加工过程列表", description = "企业微信端船模加工过程列表", tags = {"WechatController"})
    @ApiResponses(value = {@ApiResponse(responseCode = "200",description = "",content ={@Content(schema = @Schema(implementation = WechatShipModelVO.class))} )})
    public FebsResponse getShipModelProcs(@Parameter(name = "船模主键id",description = "JSON格式",required = true)String id){
        List<ModelShipProcess> list =  modelShipService.getModelShipProcsByShipId(id);
        List<WechatShipModelProcVO> voList = new ArrayList<WechatShipModelProcVO>();
        if(CollectionUtil.isNotEmpty(list)){
            for(ModelShipProcess proc : list){
                WechatShipModelProcVO vo = new WechatShipModelProcVO();
                BeanUtil.copyProperties(proc, vo);
                if(vo.getStartDate() != null && vo.getEndDate() != null){
                   long day = DateUtil.between(vo.getStartDate(), vo.getEndDate(), DateUnit.DAY, true);
                    vo.setWorkTime(day * 8);
                }else{
                    vo.setWorkTime(0L);
                }
                voList.add(vo);
            }
        }
        return success(voList);
    }

    @CrossOrigin
    @GetMapping("/getOperatorList")
    @ResponseBody
    @Operation(summary = "企业微信端船模加工过程操作人员下拉列表", description = "企业微信端船模加工过程操作人员下拉列表", tags = {"WechatController"})
    public FebsResponse getOperatorList(){
        List<User> userList = getUsersByRoleId("533f1044ed1db628316a3e7c35305fd8", "0");
        List<WechatOperatorVO> voList = new ArrayList<WechatOperatorVO>();
        if(CollectionUtil.isNotEmpty(userList)){
            for(User user : userList){
                WechatOperatorVO vo = new WechatOperatorVO();
                BeanUtil.copyProperties(user,vo);
                voList.add(vo);
            }
        }
        return success(voList);
    }

    @CrossOrigin
    @GetMapping("/getOarsModelList")
    @ResponseBody
    @Operation(summary = "企业微信端桨模列表", description = "企业微信端桨模列表", tags = {"WechatController"})
    @ApiResponses(value = {@ApiResponse(responseCode = "200",description = "",content ={@Content(schema = @Schema(implementation = WechatShipModelVO.class))} )})
    public FebsResponse getOarsModelList(@Parameter(name = "企业微信端桨模列表",description = "JSON格式",required = true)WechatModelParams params){
        List<WechatOarsModelVO> list =  modelOarsService.getOarsModelList(params);
        return success(list);
    }

    @CrossOrigin
    @GetMapping("/getAttachModelList")
    @ResponseBody
    @Operation(summary = "企业微信端附体列表", description = "企业微信端附体列表", tags = {"WechatController"})
    @ApiResponses(value = {@ApiResponse(responseCode = "200",description = "",content ={@Content(schema = @Schema(implementation = WechatShipModelVO.class))} )})
    public FebsResponse getAttachModelList(@Parameter(name = "企业微信端附体列表",description = "JSON格式",required = true)WechatModelParams params){
        List<WechatAttachModelVO> list =  modelAttachService.getAttachModelList(params);
        return success(list);
    }

    /**
    * 上传图纸
     * @author ganjun
     * @date 2024-11-17 19:03:49
            */
    @CrossOrigin
    @Log("企业微信modelShip上传图纸")
    @PostMapping("/modelShip/uploadChart")
    @Operation(summary = "企业微信端船模上传文件", description = "企业微信端船模上传文件", tags = {"WechatController"})
    @ResponseBody
    public FebsResponse uploadChart(@RequestBody @Parameter(name = "船模加工流程传入参数",description = "JSON格式",required = true)ShipModelProcParams params){
        try {
            params.setOperator(getCurrentUser().getUserName());
            modelShipService.uploadChart(params);
            return success();
        } catch (Exception ex) {
            return failure(ex,"提交失败");
        }

    }

    /**
     * 下料
     * @author ganjun
     * @date 2024-11-17 19:03:49
     */
    @CrossOrigin
    @Log("企业微信modelShip下料")
    @PostMapping("/modelShip/cutting")
    @Operation(summary = "企业微信端船模下料", description = "企业微信端船模下料", tags = {"WechatController"})
    @ResponseBody
    public FebsResponse cutting(@RequestBody @Parameter(name = "船模加工流程传入参数",description = "JSON格式",required = true) ShipModelProcParams params){
        try {
            params.setOperator(getCurrentUser().getUserName());
            modelShipService.cutting(params);
            return success();
        } catch (Exception ex) {
            return failure(ex,"提交失败");
        }
    }

    /**
     * 粗切
     * @author ganjun
     * @date 2024-11-17 19:03:49
     */
    @CrossOrigin
    @Log("企业微信modelShip粗切")
    @PostMapping("/modelShip/roughCut")
    @Operation(summary = "企业微信端船模粗切", description = "企业微信端船模粗切", tags = {"WechatController"})
    @ResponseBody
    public FebsResponse roughCut(@RequestBody @Parameter(name = "船模加工流程传入参数",description = "JSON格式",required = true) ShipModelProcParams params){
        try {
            params.setOperator(getCurrentUser().getUserName());
            modelShipService.routhCut(params);
            return success();
        } catch (Exception ex) {
            return failure(ex,"提交失败");
        }
    }

    /**
     * 精切
     * @author ganjun
     * @date 2024-11-17 19:03:49
     */
    @CrossOrigin
    @Log("企业微信modelShip精切")
    @PostMapping("/modelShip/fineCut")
    @Operation(summary = "企业微信端船模精切", description = "企业微信端船模精切", tags = {"WechatController"})
    @ResponseBody
    public FebsResponse fineCut(@RequestBody @Parameter(name = "船模加工流程传入参数",description = "JSON格式",required = true) ShipModelProcParams params){
        try {
            params.setOperator(getCurrentUser().getUserName());
            modelShipService.fineCut(params);
            return success();
        } catch (Exception ex) {
            return failure(ex,"提交失败");
        }
    }

    /**
     * 修模
     * @author ganjun
     * @date 2024-11-17 19:03:49
     */
    @CrossOrigin
    @Log("企业微信modelShip修模")
    @PostMapping("/modelShip/modRepair")
    @Operation(summary = "企业微信端船模修模", description = "企业微信端船模修模", tags = {"WechatController"})
    @ResponseBody
    public FebsResponse modRepair(@RequestBody @Parameter(name = "船模加工流程传入参数",description = "JSON格式",required = true) ShipModelProcParams params){
        try {
            params.setOperator(getCurrentUser().getUserName());
            modelShipService.modRepair(params);
            return success();
        } catch (Exception ex) {
            return failure(ex,"提交失败");
        }
    }

    /**
     * 油漆
     * @author ganjun
     * @date 2024-11-17 19:03:49
     */
    @CrossOrigin
    @Log("企业微信modelShip油漆")
    @PostMapping("/modelShip/paint")
    @Operation(summary = "企业微信端船模油漆", description = "企业微信端船模油漆", tags = {"WechatController"})
    @ResponseBody
    public FebsResponse paint(@RequestBody @Parameter(name = "船模加工流程传入参数",description = "JSON格式",required = true)ShipModelProcParams params){
        try {
            params.setOperator(getCurrentUser().getUserName());
            modelShipService.paint(params);
            return success();
        } catch (Exception ex) {
            return failure(ex,"提交失败");
        }
    }


    /**
     * 完成
     * @author ganjun
     * @date 2024-11-17 19:03:49
     */
    @CrossOrigin
    @Log("企业微信modelShip完成")
    @PostMapping("/modelShip/finish")
    @Operation(summary = "企业微信端船模已有、外带，完成操作", description = "企业微信端船模已有、外带，完成操作", tags = {"WechatController"})
    @ResponseBody
    public FebsResponse modelShipFinish(@RequestBody @Parameter(name = "船模加工流程传入参数",description = "JSON格式",required = true)ShipModelProcParams params){
        try {
            params.setOperator(getCurrentUser().getUserName());
            modelShipService.finish(params);
            return success();
        } catch (Exception ex) {
            return failure(ex,"提交失败");
        }
    }


    /**
     * 桨模完成操作
     * @author ganjun
     * @date 2024-11-17 19:03:49
     */
    @CrossOrigin
    @Log("企业微信modelOars完成")
    @PostMapping("/modelOarsFinish")
    @Operation(summary = "企业微信端桨模完成操作", description = "企业微信端桨模完成操作", tags = {"WechatController"})
    @ResponseBody
    public FebsResponse modelOarsFinish(@RequestBody @Parameter(name = "企业微信端桨模、附体完成操作传入参数",description = "JSON格式",required = true) WechatFinishParams params){
        try {
            modelOarsService.finishForWechat(params);
            return success();
        } catch (Exception ex) {
            return failure(ex,"企业微信端桨模完成操作失败");
        }
    }

    /**
     * 附体完成操作
     * @author ganjun
     * @date 2024-11-17 19:03:49
     */
    @CrossOrigin
    @Log("企业微信modelAttach完成")
    @PostMapping("/modelAttachFinish")
    @Operation(summary = "企业微信端附体完成操作", description = "企业微信端附体完成操作", tags = {"WechatController"})
    @ResponseBody
    public FebsResponse modelAttachFinish(@RequestBody @Parameter(name = "企业微信端桨模、附体完成操作传入参数",description = "JSON格式",required = true) WechatFinishParams params){
        try {
            modelAttachService.finishForWechat(params);
            return success();
        } catch (Exception ex) {
            return failure(ex,"企业微信端附体完成操作失败");
        }
    }

    /**
     * 附件上传
     * @param plupload
     * @param request
     * @return
     */
    @CrossOrigin
    @RequestMapping(value = "/upload/file", method = RequestMethod.POST)
    @ResponseBody
    public FebsResponse uploadFile(Plupload plupload, HttpServletRequest request) {
        if (!checkFileType(plupload.getName(), allowOtherFiles)) {
            return new FebsResponse().fail().message("不支持的文件类型！");
        }
        FebsResponse objects = fileUpCommon(plupload, request, "files");
        return objects;
    }


    /**
     * 文件类型判断
     *
     * @param fileName
     * @return
     */
    private static boolean checkFileType(String fileName, String[] allowFiles) {
        Iterator<String> type = Arrays.asList(allowFiles).iterator();
        while (type.hasNext()) {
            String ext = type.next();
            if (fileName.toLowerCase().endsWith(ext)) {
                return true;
            }
        }
        return false;
    }

    public static FebsResponse fileUpCommon(Plupload plupload, HttpServletRequest request, String path) {
        plupload.setRequest(request);
        try {
            String videoPath = path + "/" + DateFormatUtils.format(System.currentTimeMillis(), "yyyyMMdd");
            File dir = new File(UploadPathUtil.getRootPath() + videoPath);
            //上传文件
            PluploadUtil.upload(plupload, dir);
            //判断文件是否上传成功（被分成块的文件是否全部上传完成）
            if (PluploadUtil.isUploadFinish(plupload)) {
                //File uploadFile = new File(dir.getPath(), plupload.getFileName());
                //String imageName = plupload.getFileName().substring(plupload.getFileName().lastIndexOf(".") + 1) + ".jpg";
                //Video2ImageUtil.randomGrabberFFmpegImage(uploadFile.getPath(), dir.getPath(), imageName);
                Map<String, Object> data = new HashMap<>();
                data.put("fileName", plupload.getFileName());
                data.put("filePath", "files/" + videoPath + "/" + plupload.getFileName());
                data.put("smallPath", "files/" + videoPath + "/" + plupload.getSmallFileName());
                data.put("message", plupload.getChunk() + "," + plupload.getName() + "," + plupload.getChunks());
                return new FebsResponse().success().data(data);
            } else {
                return new FebsResponse().success().message(plupload.getChunk() + "," + plupload.getName() + "," + plupload.getChunks());
            }
        } catch (Exception e) {
            return new FebsResponse().fail().message("文件上传失败！Error：" + e.getMessage());
        }
    }


    @Log("试验排期计划")
    @CrossOrigin
    @GetMapping("/scheduelList")
  //  @RequiresPermissions("schedule:view")
    @Operation(summary = "试验排期计划", description = "试验排期计划", tags = {"WechatController"})
    @ResponseBody
    public FebsResponse  scheduelList(TaskDto taskDto){
        try {
         List<TaskDto>  list=  scheduleService.getAssembledTask(taskDto);
            return new FebsResponse().success().data(list);
        } catch (Exception ex) {
            return failure(ex,"企业微信端附体完成操作失败");
        }
    }
}
